﻿using Microsoft.Extensions.Configuration;
using MQTT.Share.Helper;
using System.IO;

namespace MQTT.Share.ConfigurationExtension
{
    public class ConfigurationManager : IConfigurationManager
    {

        public IConfiguration Configuration { get; set; }

        public static IConfigurationRoot BuildConfiguration(string path = "")
        {
            try
            {
                FileInfo assemblyFile = new FileInfo(typeof(ConfigurationManager).Assembly.Location);
                string directoryName = assemblyFile.DirectoryName;
                if (DebugHelper.IsDebug)
                {
                    directoryName = assemblyFile.Directory.Parent.Parent.Parent.FullName;
                }
                if (!File.Exists(Path.Combine(directoryName, "appsettings.json")))
                {
                    return null;
                }
                return new ConfigurationBuilder()
                    .SetBasePath(string.IsNullOrWhiteSpace(path) ? directoryName : path)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .Build();
            }
            catch (System.Exception)
            {
                return null;
            }

        }

        public string GetConfig(string key)
        {
            if (Configuration == null) return string.Empty;
            return Configuration[key];
        }

        public int GetConfigInt(string key)
        {
            if (Configuration == null) return 0;
            int result = 0;
            int.TryParse(Configuration[key], out result);
            return result;
        }
    }
}
